﻿using ICMS.PluginInterfaces;
using commonImportPlugin.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using commonImportPlugin.Config;
using commonImportPlugin.Configs.SsseFile;

namespace commonImportPlugin.FilesCore.SsseFile
{
    public class SsseBaseExcel : CommonUtil
    {
        SsseCommonBase commonBase = new SsseCommonBase();
        /// <summary>
        /// 将excel表格转为Dataset
        /// </summary>
        /// <param name="filePath">excel文件的路径</param>
        /// <returns>DataSet</returns>
        public DataSet excelToDataSet(string filePath)
        {
            DataSet dataset;
            string stringConnect = null;

            if (Path.GetExtension(filePath) == ".xls")
            {
                stringConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
            }
            else
            {
                stringConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
            }

            OleDbConnection myConn = new OleDbConnection(stringConnect);
            string strCom = " SELECT * FROM [Sheet1$]";
            try
            {
                myConn.Open();
            }
            catch
            {
                MessageBox.Show("打开excel失败!");
                myConn.Close();
                return null;
            }

            OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
            dataset = new DataSet();
            myCommand.Fill(dataset);
            myConn.Close();
            return dataset;
        }
        /// <summary>
        /// 获取社保数据通用函数(excel格式）
        /// </summary>
        /// <param name="ssseFilePath">社保文件</param>
        /// <param name="dataIndex">社保数据开始位置(1开始)</param>
        /// <param name="ssCardIdColumn">社保卡号所处列</param>
        /// <returns>社保数据</returns>
        public List<ICData> getSsseAllDatas(string ssseFilePath, SsseFileConfigExcel config)
        {
            DataSet originSsseDatas = null;//所有初始社保数据         
            ICData ssseIcData = null;
            int[] subRules = null;

            if (!File.Exists(ssseFilePath))
                throw new Exception("社保文件不存在！");

            originSsseDatas = excelToDataSet(ssseFilePath);

            List<ICData> finalSsseIcDatas = new List<ICData>();

            foreach (DataRow dr in originSsseDatas.Tables[0].Rows)
            {
                string ssseData = null;
                ssseIcData = new ICData();
                int column = 1;
                foreach (DataColumn dataColumn in originSsseDatas.Tables[0].Columns)
                {
                    ssseData += dr[dataColumn].ToString() + "|";
                    //身份证号
                    if (config.subPersonIdRules != null && column == config.subPersonIdRules[0])
                    {
                        subRules = config.subPersonIdRules;
                        ssseIcData.PersonID = SubString(dr[dataColumn].ToString().Trim(), subRules[1], subRules[2]);
                    }
                    //社保卡号
                    if (config.subCardIdRules != null && column == config.subCardIdRules[0])
                    {
                        subRules = config.subCardIdRules;
                        ssseIcData.SSCardID = SubString(dr[dataColumn].ToString().Trim(), subRules[1], subRules[2]);
                    }
                    //银行卡号
                    if (config.subBankCardIdRules != null && column == config.subBankCardIdRules[0])
                    {
                        subRules = config.subBankCardIdRules;
                        ssseIcData.BankCardID = SubString(dr[dataColumn].ToString().Trim(), subRules[1], subRules[2]);
                    }
                    column++;
                }
                string ssData = ssseData.Trim('|');

                if (string.IsNullOrEmpty(ssData))
                    break;

                //检查格式              
                if (!string.IsNullOrEmpty(config.dataCheckRegexs))
                    commonBase.ssseDataCheck(ssseIcData, config.dataCheckRegexs);

                ssseIcData.SSData = ssData;
                ssseIcData.Extend1 = Path.GetFileNameWithoutExtension(ssseFilePath) + ".txt";
                finalSsseIcDatas.Add(ssseIcData);

            }
            return finalSsseIcDatas;

        }
    }
    public class SsseBaseGerneral : CommonUtil
    {
        SsseCommonBase commonBase = new SsseCommonBase();
        /// <summary>
        /// 获取社保通用函数
        /// </summary>
        /// <param name="ssseFilePath">社保文件</param>
        /// <param name="dataIndex">社保数据开始位置(1开始)</param>
        /// <param name="ssseSeparators">社保数据分割赋</param>
        /// <param name="rules">分别表示银行卡号、身份证号、社保卡号、医保卡号 配置(-1,2,5)-1表无，2表示分割所在第2列(0开始）</param>
        /// <returns>社保数据</returns>
        public List<ICData> getSsseAllDatas(string ssseFilePath, SsseFileConfig config)
        {
            string[] originSsseLines = null;//所有初始社保数据
            string[] idsDatas = new string[4];//idsDatas[0]银行卡号，idsDatas[1]身份证号，idsDatas[2]社保卡号,idsDatas[3]医保卡号         
            ICData ssseIcData = null;
            int[] subRules = null;

            List<ICData> allSsseIcDatas = new List<ICData>();

            if (!File.Exists(ssseFilePath))
                throw new Exception("社保文件不存在！");
            try
            {
                originSsseLines = File.ReadAllLines(ssseFilePath, Encoding.GetEncoding(config.encoding));
                for (int i = config.dataIndex - 1; i < originSsseLines.Length; i++)
                {
                    string[] ssseDatas = originSsseLines[i].Split(config.dataSeparators, StringSplitOptions.None);

                    ///////////获取银行、身份证、社保卡，医保号/////
                    #region 银行、身份证、社保卡，医保
                    ssseIcData = new ICData();//社保数据
                    if (config.subBankCardId != null)
                    {
                        subRules = config.subBankCardId;
                        ssseIcData.BankCardID = SubString(ssseDatas[subRules[0] - 1].Trim(), subRules[1], subRules[2]);
                    }
                    if (config.subPersonId != null)
                    {
                        subRules = config.subPersonId;
                        ssseIcData.PersonID = SubString(ssseDatas[subRules[0] - 1].Trim(), subRules[1], subRules[2]);//身份证号
                    }
                    if (config.subCardId != null)
                    {
                        subRules = config.subCardId;
                        ssseIcData.SSCardID = SubString(ssseDatas[subRules[0] - 1].Trim(), subRules[1], subRules[2]);//社保卡号
                    }
                    #endregion

                    //检查格式              
                    if (!string.IsNullOrEmpty(config.dataCheckRegexs))
                        commonBase.ssseDataCheck(ssseIcData, config.dataCheckRegexs);

                    ssseIcData.SSData = originSsseLines[i];//社保数据
                    ssseIcData.Extend1 = Path.GetFileName(ssseFilePath);// 社保文件名
                    allSsseIcDatas.Add(ssseIcData);
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message); ;
            }
            return allSsseIcDatas;
        }
    }
    public class SsseCommonBase : CommonUtil
    {
        /// <summary>
        /// 社保数据格式检查
        /// </summary>
        /// <param name="ssseIcData">社保数据</param>
        /// <param name="ssseDataRegexs">数据格式匹配正则表达式</param>
        /// <returns></returns>
        public bool ssseDataCheck(ICData ssseIcData, string ssseDataRegexs)
        {
            Match match = null;
            bool isSucceed = true;
            string errorMessage = null;

            string[] seperaters = new string[] { "[#]" };//分隔符
            string[] regexs = ssseDataRegexs.Split(seperaters, StringSplitOptions.None);

            for (int i = 0; i < regexs.Length; i++)
            {
                switch (i)
                {
                    case 0:
                        {
                            /////////////////银行卡号////////////
                            if (!string.IsNullOrEmpty(regexs[i].Trim()) && isSucceed)
                            {
                                if (string.IsNullOrEmpty(ssseIcData.BankCardID))
                                {
                                    isSucceed = false;
                                    errorMessage = "社保数据中提取的银行卡号为空";
                                }
                                else
                                {
                                    match = Regex.Match(ssseIcData.BankCardID.Trim(), regexs[i].Trim());
                                    if (!match.Success)
                                    {
                                        isSucceed = false;
                                        errorMessage = "提取的银行卡号格式不正确";
                                    }

                                }
                            }
                        }
                        break;
                    case 1:
                        {
                            /////////////////身份证号////////////
                            if (!string.IsNullOrEmpty(regexs[i].Trim()) && isSucceed)
                            {
                                if (string.IsNullOrEmpty(ssseIcData.PersonID))
                                {
                                    isSucceed = false;
                                    errorMessage = "社保数据中提取的身份证号为空";
                                }
                                else
                                {
                                    match = Regex.Match(ssseIcData.PersonID.Trim(), regexs[i].Trim());
                                    if (!match.Success)
                                    {
                                        isSucceed = false;
                                        errorMessage = "提取的身份证号格式不正确";
                                    }
                                }

                            }
                        }
                        break;
                    case 2:
                        {
                            /////////////////社保卡号////////////
                            if (!string.IsNullOrEmpty(regexs[i].Trim()) && isSucceed)
                            {
                                if (string.IsNullOrEmpty(ssseIcData.SSCardID))
                                {
                                    isSucceed = false;
                                    errorMessage = "社保数据中提取的医保卡号为空";
                                }
                                else
                                {
                                    match = Regex.Match(ssseIcData.SSCardID.Trim(), regexs[i].Trim());
                                    if (!match.Success)
                                    {
                                        isSucceed = false;
                                        errorMessage = "提取的社保号格式不正确";
                                    }
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
            }

            if (!isSucceed)
                throw new Exception(errorMessage);

            return isSucceed;
        }
    }
}
